﻿(function () {
    /* Copyright 2010 Imaginary Development. All rights reserved*/
    function DoOnceJquerified() {
        if (typeof ($jq) == 'undefined') {
            if (typeof ($) != 'undefined') {
                $jq = $;
            } else {
                return alert('$jq->jquerify not defined');
            }
        }
        Number.prototype.Thousand = function () { return this * 1000; };
        Number.prototype.Million = function () { return this.Thousand() * 1000; };
        if ($jq('html#facebook').length > 0) {
            alert("Script doesn't work in facebook");
            throw ("Facebook detected");
        }

        //Analyzer

        var firstRound = $jq('div.battle_log div.round:first');
        if (firstRound.length == 0) {
            alert('Failed to find first round of battle');
            throw "Failed to find first round of battle";
        }
        var finalRound = $jq('div.battle_log div.round.alt:last');
        var allCombatants = new Array();

        function BaseShip() {
            this.Attack = -1;
            this.Shield = -1;
            this.Hull = -1;
            this.MakesDebris = null;

            this.InitializeAll = function (attack, shield, hull, makesDebris, ore, crystal, hydro) {
                this.Attack = attack;
                this.Shield = shield;
                this.Hull = hull;
                this.MakesDebris = makesDebris || false;
                this.OreCost = ore || 0;
                this.CrystalCost = crystal || 0;
                this.HydrogenCost = hydro || 0;
            }; //end InitializeAll
            this.Debris = function (count) {
                if (this.MakesDebris == true) {
                    return { OreDebris: (this.OreCost * count) || 0, CrystalDebris: (this.CrystalCost * count) || 0 };
                } // end if
                return { OreDebris: 0, CrystalDebris: 0 };
            } //End Debris function
        }; //end BaseShip type

        function GetShipBases(shipClass) {
            var result = new BaseShip();
            result.Name = shipClass;
            switch (shipClass) {
                case 'Hermes_class': result.InitializeAll(0, 0, 100, 1, 0, 1000); break;
                case 'Solar_satellite': /*helios*/result.InitializeAll(1, 1, 200, 1, 0, 2000, 500); break;
                case 'Artemis_class': result.InitializeAll(50, 10, 400, 1, 3000, 1000); break;
                case 'Atlas_class': result.InitializeAll(5, 10, 400, 1, 2000, 2000); break;
                case 'Apollo_class': result.InitializeAll(150, 25, 850, 1, 6000, 2500); break;
                case 'Charon_class': result.InitializeAll(1, 25, 800, 1, 4000, 4000, 1000); break;
                case 'Hercules_class': result.InitializeAll(5, 25, 1200, 1, 6000, 6000); break;
                case 'Dionysus_class': result.InitializeAll(1, 10, 1600, 1, (10).Thousand(), 6000, 2000); break;
                case 'Poseidon_class': result.InitializeAll(400, 50, 2700, 1, 20000, 7000, 2000); break;
                case 'Gaia_class': result.InitializeAll(50, 100, 3000, 1, (10).Thousand(), (20).Thousand(), (10).Thousand()); break;
                case 'Athena_class': result.InitializeAll(1000, 200, 6000, 1, (45).Thousand(), (15).Thousand()); break;
                case 'Ares_class': result.InitializeAll(1000, 500, 7500, 1, (50).Thousand(), (25).Thousand(), (15).Thousand()); break;
                case 'Hades_class': result.InitializeAll(700, 400, 7000, 1, (30).Thousand(), (40).Thousand(), (15).Thousand()); break;
                case 'Prometheus_class': result.InitializeAll(2000, 500, (11).Thousand(), 1, (60).Thousand(), (50).Thousand(), (15).Thousand()); break;

                case 'Missile_turret': result.InitializeAll(80, 20, 200, 0, 2000); break;
                case 'Laser_turret': result.InitializeAll(100, 25, 200, 0, 1500, 500); break;
                case 'Pulse_cannon': result.InitializeAll(250, 100, 800, 0, 6000, 2000); break;
                case 'Particle_cannon': result.InitializeAll(150, 500, 800, 0, 2000, 6000); break;
                // case ABM?                 
                case 'Decoy': result.InitializeAll(0, 2000, 2000, 0, (10).Thousand(), (10).Thousand()); break;
                // case IBM?           
                case 'Gauss_cannon': result.InitializeAll(1100, 200, 3500, 0, (20).Thousand(), (15).Thousand(), 2000); break;
                case 'Large_decoy': result.InitializeAll(0, (10).Thousand(), (10).Thousand(), 0, (50).Thousand(), (50).Thousand()); break;
                case 'Plasma_turret': result.InitializeAll(3000, 300, (10).Thousand(), 0, (50).Thousand(), (50).Thousand(), (30).Thousand()); break;

                default:
                    break;
            } // end switch
            return result;
        } //end function Get Ship Bases


        GetNumber = function (combatant, currentShipDom, shipClass) {
            var currentShipNumber = $jq('div.number:not(.header)', currentShipDom);

            var currentShipText = currentShipNumber.text().substring(1).replace(',', '');

            if (typeof (currentShipText) != 'string')
                throw ("Text parse error");
            if (currentShipText.length == 0)
                throw ("Could not locate final ship text for " + shipClass + " for player " + $jq(combatant.NameDom).text());
            var resultNumber = parseInt(currentShipText, 10);
            if (typeof (resultNumber) != 'number')
                console.log('resultNumber=' + typeof (resultNumber) + ' ' + resultNumber);
            return resultNumber;
        } //end GetNumber


        ProcessShip = function (combatant, shipDom) {
            var shipClass = $jq('div.image img', shipDom).attr('alt');
            var shipCount = GetNumber(combatant, shipDom, shipClass);
            if (combatant.AllTechsFound !== true)
                combatant.Assemble(shipDom, shipCount);
            Lost = shipCount; //set to all in case there are none left.

            if (combatant.FinalNameDom && combatant.FinalNameDom.length == 1) {//User made it to final round

                var finalCombatantShips = $jq($jq('~ div.ships', combatant.FinalNameDom)[0]);


                var finalShipListDom = $jq('div.ship:not(.header)', finalCombatantShips);
                if (finalShipListDom.length <= 0)
                    console.log("fsld=" + finalShipListDom.length);
                var finalShipDomFilter = 'div.image img[alt=' + shipClass + ']';

                var finalShipDom = finalShipListDom.has(finalShipDomFilter);

                if (finalShipDom.length <= 0)
                    throw ("debug stop, did not find first ship");
                if (finalShipDom && finalShipDom.length == 1) {


                    var finalNumber = GetNumber(combatant, finalShipDom, shipClass);

                    Lost = shipCount - finalNumber;
                } // end finalNumberDom if
            } // end combatant.FinalNameDom if

            $jq(shipDom).append('<div class="lost">' + Lost + '</div>'); //Display lost result


        } //end function ProcessShip



        function ProcessCombatant(combatant, shipsDom) {
            if (typeof (combatant.FinalNameDom) != 'undefined')
                $jq('div.ship.header', shipsDom).append('<div class="lost">Lost</div>');
            $jq('div.ship:not(.header)', shipsDom).each(function (shipIndex, ship) {
                if (typeof (combatant) == 'undefined')
                    throw "no combatant error";

                ProcessShip(combatant, ship);
            }); // end ship each loop
        } //end ProcessCombatant


        function Combatant() {
            this.WeaponTech = -1;
            this.ArmorTech = -1;
            this.ShieldTech = -1;
            this.AllTechsFound = function () {
                return this.WeaponTech >= 0 && this.ArmorTech >= 0 && this.ShieldTech >= 0;
            }
            this.TechOrQ = function (tech) {
                if (tech >= 0)
                    return Math.ceil(tech);
                return '?';
            }
            this.Output = function () {
                return 'W/A/S - ' + this.TechOrQ(this.WeaponTech) + '/' + this.TechOrQ(this.ArmorTech) +
                    '/' + this.TechOrQ(this.ShieldTech);
            };
            this.Assemble = function (shipDom, number) {
                var shipBases = GetShipBases($jq('div.image img', shipDom).attr('alt'));

                if (typeof (number) != 'number')
                    number = parseInt($jq('div.number:not(.header)', shipDom).text().substring(1), 10);

                if (this.WeaponTech < 0 && (shipBases == null || shipBases.Attack > 0)) {
                    var weapon = parseInt($jq('div.attack_strength', shipDom).text().replace(',', ''), 10) / number;

                    if (weapon >= 50) {
                        if (shipBases.Attack > 50) {
                            var wTech = (weapon - shipBases.Attack) * 10 / shipBases.Attack;
                            this.WeaponTech = wTech;
                        }
                    }
                }
                if (this.ArmorTech < 0 && (shipBases == null || shipBases.Hull > 0)) {
                    var hull = parseInt($jq('div.hull', shipDom).text().replace(',', ''), 10) / number;
                    var aTech = (hull - shipBases.Hull) * 10 / shipBases.Hull;
                    this.ArmorTech = aTech;
                }
                if (this.ShieldTech < 0 && (shipBases == null || shipBases.Shield > 0)) {
                    var shield = parseInt($jq('div.shield_strength', shipDom).text().replace(',', ''), 10) / number;
                    if (shield >= 10) {
                        var tech = (shield - shipBases.Shield) * 10 / shipBases.Shield;
                        this.ShieldTech = tech;
                    }
                }

            } //end function assemble

        } //end combatant

        function ParseCombatants(selector) {
            //var firstOnly=':first';
            var allCombatantsInSelector = $jq(selector, firstRound);
            allCombatantsInSelector.each(function (index, nameDom) {
                var combatant = new Combatant();
                combatant.NameDom = nameDom;
                allCombatants[index] = combatant;
                combatant.NameText = $jq(combatant.NameDom).text();
                var finalNameSelector = 'div.name:contains("' + combatant.NameText + '")';

                var finalNameDom = $jq(finalNameSelector, finalRound);

                combatant.FinalNameDom = finalNameDom;
                if (typeof (finalNameDom) == 'undefined')
                    console.log('Could not find FinalNameDom for ' + combatant.NameText);

                var shipsDom = $jq($jq('~ div.ships', nameDom)[0]); //get ships of combatant

                if (shipsDom.length > 0)//may not have ships if defenses only?
                    ProcessCombatant(combatant, shipsDom);
                $jq(nameDom).text(combatant.NameText + combatant.Output()); //output techs


            }); // end allCombatantsInSelector each loop
        } //end function ParseCombatants


        ParseCombatants("div.name");
        // end *analyzer*

    } //end doOnceJquerified

    var el = document.createElement('div'), b = document.getElementsByTagName('body')[0]; otherlib = false, msg = ''; el.style.position = 'fixed'; el.style.height = '32px'; el.style.width = '220px'; el.style.marginLeft = '-110px'; el.style.top = '0'; el.style.left = '50%'; el.style.padding = '5px 10px 5px 10px'; el.style.zIndex = 1001; el.style.fontSize = '12px'; el.style.color = '#222'; el.style.backgroundColor = '#f99'; if (typeof jQuery != 'undefined') {
        msg = 'This page already using jQuery v' + jQuery.fn.jquery;
        DoOnceJquerified();
        return showMsg();
    } else if (typeof $ == 'function') { otherlib = true; } function getScript(url, success) { var script = document.createElement('script'); script.src = url; var head = document.getElementsByTagName('head')[0], done = false; script.onload = script.onreadystatechange = function () { if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) { done = true; success(); } }; head.appendChild(script); } getScript('http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', function () {
        if (typeof jQuery == 'undefined') { msg = 'Sorry, but jQuery wasn\'t able to load'; } else {

            msg = 'This page is now jQuerified with v' + jQuery.fn.jquery; if (otherlib) { msg += ' and noConflict(). Use $jq(), not $().'; }
            /* Begin AjaxBookmarklet.js */
            DoOnceJquerified();
            /* End AjaxBookmarklet.js */
        } return showMsg();
    }); function showMsg() { el.innerHTML = msg; b.appendChild(el); window.setTimeout(function () { if (typeof jQuery == 'undefined') { b.removeChild(el); } else { jQuery(el).fadeOut('slow', function () { jQuery(this).remove(); }); if (otherlib) { $jq = jQuery.noConflict(); } } }, 2500); }
})();
